<style lang="less">
@import "./menuManage.less";
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="addMenu" type="primary" icon="md-add">添加子节点</Button>
        <Button @click="addRootMenu" icon="md-add">添加顶部菜单</Button>
        <!-- <Button @click="delAll"
        icon="md-trash">批量删除</Button>-->
        <Dropdown @on-click="handleDropdown">
          <Button>
            更多操作
            <Icon type="md-arrow-dropdown"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <!-- <DropdownItem name="refresh">刷新</DropdownItem> -->
            <DropdownItem name="expandOne">收合所有</DropdownItem>
            <DropdownItem name="expandTwo">仅展开一级</DropdownItem>
            <DropdownItem name="expandThree">仅展开两级</DropdownItem>
            <DropdownItem name="expandAll">展开所有</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <!-- <i-switch v-model="strict" size="large" style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>-->
      </Row>
      <Row type="flex" justify="start" class="code-row-bg">
        <Col span="6">
          <Alert show-icon>
            当前选择编辑：
            <span class="select-title">{{editTitle}}</span>
            <a class="select-clear" v-if="menuForm.id" @click="cancelEdit">取消选择</a>
          </Alert>
          <div class="tree-bar" :style="{maxHeight: maxHeight}">
            <Tree
              ref="tree"
              :data="data"
              :render="renderContent"
              @on-check-change="changeSelect"
              :check-strictly="!strict"
              children-key="children"
            ></Tree>
          </div>
          <Spin size="large" fix v-if="loading"></Spin>
        </Col>
        <Col span="9" style="margin-left:10px">
          <Form ref="menuForm" :model="menuForm" :label-width="100" :rules="menuFormValidate">
            <div v-if="showParent">
              <FormItem label="上级节点：">{{parentTitle}}</FormItem>
            </div>
            <FormItem label="类型" prop="level">
              <div v-show="menuForm.level==0">
                <Icon type="ios-navigate-outline" size="16" style="margin:0 5px 3px 0;"></Icon>
                <span>顶部菜单</span>
              </div>
              <div v-show="menuForm.level>0&&menuForm.type==1">
                <Icon type="ios-list-box-outline" size="16" style="margin:0 5px 3px 0;"></Icon>
                <span>页面菜单</span>
              </div>
              <div v-show="menuForm.type==2">
                <Icon type="md-radio-button-on" size="16" style="margin:0 5px 3px 0;"></Icon>
                <span>操作按钮</span>
              </div>
            </FormItem>
            <FormItem label="名称" prop="title">
              <Input v-model="menuForm.title" />
            </FormItem>
            <FormItem label="英文名" prop="code">
              <Tooltip placement="right" content="需唯一">
                <Input v-model="menuForm.code" />
              </Tooltip>
            </FormItem>
            <FormItem label="路径" prop="path" v-if="menuForm.type!==2">
              <Input v-model="menuForm.path" />
            </FormItem>
            <FormItem label="图标" prop="icon" v-if="menuForm.type!==2">
              <icon-choose v-model="menuForm.icon"></icon-choose>
            </FormItem>
            <FormItem label="前端组件" prop="component" v-if="menuForm.type==1&&menuForm.level>0">
              <Input v-model="menuForm.component" />
            </FormItem>
            <FormItem label="后台权限" prop="perms" v-if="menuForm.type==2">
              <Input v-model="menuForm.perms" />
            </FormItem>
            <FormItem label="排序值" prop="orderNum">
              <InputNumber :max="1000" :min="0" v-model="menuForm.orderNum"></InputNumber>
              <span style="margin-left:5px">值越小越靠前，支持整数</span>
            </FormItem>
            <Form-item>
              <Button
                style="margin-right:5px"
                @click="submitEdit"
                :loading="submitLoading"
                type="primary"
                icon="ios-create-outline"
              >修改并保存</Button>
              <Button @click="handleReset">重置</Button>
              <Button @click="remove">删除</Button>
            </Form-item>
          </Form>
        </Col>
      </Row>
    </Card>

    <Modal
      draggable
      :title="modalTitle"
      v-model="menuModalVisible"
      :mask-closable="false"
      :width="500"
      :styles="{top: '30px'}"
    >
      <Form ref="menuFormAdd" :model="menuFormAdd" :label-width="100" :rules="menuFormValidate">
        <div v-if="showParent">
          <FormItem label="上级节点：">{{parentTitle}}</FormItem>
        </div>
        <FormItem label="类型" prop="type">
          <div v-show="menuFormAdd.level==0">
            <Icon type="ios-navigate-outline" size="16" style="margin:0 5px 3px 0;"></Icon>
            <span>顶部菜单</span>
          </div>
          <div v-show="menuFormAdd.level>0&&menuFormAdd.type==1">
            <Icon type="ios-list-box-outline" size="16" style="margin:0 5px 3px 0;"></Icon>
            <span>页面菜单</span>
          </div>
          <div v-show="menuFormAdd.type==2">
            <Icon type="md-radio-button-on" size="16" style="margin:0 5px 3px 0;"></Icon>
            <span>操作按钮</span>
          </div>
        </FormItem>
        <FormItem label="名称" prop="title">
          <Input v-model="menuFormAdd.title" />
        </FormItem>
        <FormItem label="英文名" prop="code">
          <Tooltip placement="right" content="需唯一">
            <Input v-model="menuFormAdd.code" />
          </Tooltip>
        </FormItem>
        <FormItem label="路径" prop="path" v-if="menuFormAdd.type!==2">
          <Input v-model="menuFormAdd.path" />
        </FormItem>
        <FormItem label="图标" prop="icon" v-if="menuFormAdd.type!==2">
          <icon-choose v-model="menuFormAdd.icon"></icon-choose>
        </FormItem>
        <FormItem label="前端组件" prop="component" v-if="menuFormAdd.type==1&&menuFormAdd.level>0">
          <Input v-model="menuFormAdd.component" />
        </FormItem>
        <FormItem label="后台权限" prop="perms" v-if="menuFormAdd.type==2">
          <Input v-model="menuFormAdd.perms" />
        </FormItem>
        <FormItem label="排序值" prop="orderNum">
          <InputNumber :max="1000" :min="0" v-model="menuFormAdd.orderNum"></InputNumber>
          <span style="margin-left:5px">值越小越靠前，支持整数</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getAllMenuList, addMenu, editMenu, deleteMenu } from "@/api/index";
import IconChoose from "@/views/my-components/icon-choose";
import util from "@/libs/util.js";
export default {
  name: "menu-manage",
  components: {
    IconChoose
  },
  data() {
    return {
      loading: true,
      strict: true,
      maxHeight: "500px",
      expandLevel: 1,
      menuModalVisible: false,
      iconModalVisible: false,
      selectList: [],
      selectCount: 0,
      showParent: false,
      parentTitle: "",
      editTitle: "",
      modalTitle: "",
      menuForm: {
        menuId: 0,
        title: "",
        icon: "",
        code: "",
        parentId: 0,
        path: "",
        component: null,
        type: 1,
        level: 0,
        orderNum: 0
      },
      menuFormAdd: {},
      menuFormValidate: {
        title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        code: [
          { required: true, message: "路由英文名不能为空", trigger: "blur" }
        ],
        icon: [{ required: true, message: "图标不能为空", trigger: "click" }],
        path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
        component: [
          { required: true, message: "前端组件不能为空", trigger: "blur" }
        ]
      },
      submitLoading: false,
      data: []
    };
  },
  methods: {
    init() {
      this.getAllMenuList();
    },

    renderContent(h, { root, node, data }) {
      let icon = "";
      if (data.level == 0) {
        icon = "ios-navigate";
      } else if (data.level == 1) {
        icon = "md-list-box";
      } else if (data.level == 2) {
        icon = "md-list";
      } else if (data.level == 3) {
        icon = "md-radio-button-on";
      } else {
        icon = "md-radio-button-off";
      }
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            cursor: "pointer"
          },
          on: {
            click: () => {
              this.selectTree(data);
            }
          }
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: icon,
                size: "16"
              },
              style: {
                "margin-right": "8px",
                "margin-bottom": "3px"
              }
            }),
            h(
              "span",
              {
                class: {
                  "ivu-tree-title": true,
                  "ivu-tree-title-selected": data.menuId == this.menuForm.menuId
                }
              },
              data.title
            )
          ])
        ]
      );
    },
    handleDropdown(name) {
      if (name == "expandOne") {
        this.expandLevel = 1;
        this.getAllMenuList();
      } else if (name == "expandTwo") {
        this.expandLevel = 2;
        this.getAllMenuList();
      } else if (name == "expandThree") {
        this.expandLevel = 3;
        this.getAllMenuList();
      }
      if (name == "expandAll") {
        this.expandLevel = 4;
        this.getAllMenuList();
      } else if (name == "refresh") {
        this.getAllMenuList();
      }
    },
    selectTree(v) {
      if (v && v.menuId != this.menuForm.menuId) {
        // 转换null为""
        for (let attr in v) {
          if (v[attr] == null) {
            v[attr] = "";
          }
        }
        let str = JSON.stringify(v);
        let menu = JSON.parse(str);
        this.menuForm = menu;
        this.editTitle = menu.title;
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.menuForm.resetFields();
      this.menuForm.menuId = "";
      delete this.menuForm.menuId;
      this.editTitle = "";
    },
    cancelAdd() {
      this.menuModalVisible = false;
    },
    handleReset() {
      let type = this.menuForm.type;
      this.$refs.menuForm.resetFields();
      this.menuForm.icon = "";
      this.menuForm.component = "";
      this.menuForm.type = type;
    },
    submitEdit() {
      this.$refs.menuForm.validate(valid => {
        if (valid) {
          if (!this.menuForm.menuId) {
            this.$Message.warning("请先点击选择要修改的菜单节点");
            return;
          }
          this.submitLoading = true;
          editMenu(this.menuForm).then(res => {
            this.submitLoading = false;
            if (res.code == 0) {
              this.$Message.success("编辑成功");
              // 标记重新获取菜单数据
              this.$store.commit("setAdded", false);
              util.initRouter(this);
              this.init();
              this.menuModalVisible = false;
            }
          });
        }
      });
    },
    submitAdd() {
      this.$refs.menuFormAdd.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.menuFormAdd.type == 2) {
            this.menuFormAdd.icon = "";
            this.menuFormAdd.component = "";
          }
          if (this.menuFormAdd.type == -1) {
            this.menuFormAdd.component = "";
          }
          addMenu(this.menuFormAdd).then(res => {
            this.submitLoading = false;
            if (res.code == 0) {
              this.$Message.success("添加成功");
              // 标记重新获取菜单数据
              this.$store.commit("setAdded", false);
              util.initRouter(this);
              this.init();
              this.menuModalVisible = false;
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    addMenu() {
      if (this.menuForm.menuId == "" || this.menuForm.menuId == null) {
        this.$Message.warning("请先点击选择一个菜单权限节点");
        return;
      }
      this.parentTitle = this.menuForm.title;
      this.modalTitle = "添加子节点(可拖动)";
      this.showParent = true;
      let type = 1;
      if (this.menuForm.level == 0) {
        type = 1;
      } else if (this.menuForm.level == 1) {
        type = 1;
      } else if (this.menuForm.level == 2) {
        type = 2;
      } else {
        this.$Modal.warning({
          title: "抱歉，不能添加啦",
          content: "仅支持2级菜单目录"
        });
        return;
      }
      let component = "";
      this.menuFormAdd = {
        menuId: 1,
        title: "",
        code: "",
        path: "",
        component: null,
        icon: "",
        perms: "",
        type: type,
        parentId: this.menuForm.menuId,
        level: Number(this.menuForm.level) + 1,
        orderNum: 0
      };
      if (this.menuForm.level == 0) {
        this.menuFormAdd.path = "/";
        this.menuFormAdd.component = "Main";
      }
      this.menuModalVisible = true;
    },
    addRootMenu() {
      this.modalTitle = "添加顶部菜单(可拖动)";
      this.showParent = false;
      this.menuFormAdd = {
        title: "",
        code: "",
        path: "",
        component: null,
        icon: "",
        type: -1,
        parentId: 0,
        level: 0,
        orderNum: 0
      };
      this.menuModalVisible = true;
    },
    changeSelect(v) {
      this.selectCount = v.length;
      this.selectList = v;
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function(e) {
            ids += e.menuId + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          deleteMenu(ids).then(res => {
            if (res.code == 0) {
              this.$Message.success("删除成功");
              // 标记重新获取菜单数据
              this.$store.commit("setAdded", false);
              util.initRouter(this);
              this.selectList = [];
              this.selectCount = 0;
              this.cancelEdit();
              this.init();
            }
          });
        }
      });
    },
    remove() {
      if (!this.menuForm.menuId) {
        this.$Message.warning("请先点击选择要删除的菜单");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除菜单 " + this.menuForm.title + " ?",
        loading: true,
        onOk: () => {
          deleteMenu(this.menuForm.menuId).then(res => {
            this.$Modal.remove();
            if (res.code == 0) {
              this.$Message.success("删除成功");
              this.menuForm = {
                menuId: 0,
                title: "",
                icon: "",
                code: "",
                parentId: 0,
                path: "",
                component: null,
                type: 1,
                level: 0,
                orderNum: 0
              };

              this.getAllMenuList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    getAllMenuList() {
      this.loading = true;
      getAllMenuList().then(res => {
        this.loading = false;
        if (res.code == 0) {
          let expandLevel = this.expandLevel;
          res.data.forEach(function(e) {
            if (expandLevel == 1) {
              if (e.level == 0) {
                e.expand = false;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (c.level == 1) {
                    c.expand = false;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function(b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            } else if (expandLevel == 2) {
              if (e.level == 0) {
                e.expand = true;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (c.level == 1) {
                    c.expand = false;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function(b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            } else if (expandLevel == 3) {
              if (e.level == 0) {
                e.expand = true;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (c.level == 1) {
                    c.expand = true;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function(b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            } else if (expandLevel == 4) {
              if (e.level == 0) {
                e.expand = true;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (c.level == 1) {
                    c.expand = true;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function(b) {
                      if (b.level == 2) {
                        b.expand = true;
                      }
                    });
                  }
                });
              }
            }
          });
          this.data = res.data;
        }
      });
    }
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
};
</script>